﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using Google.GData.Documents;
using System.Collections.ObjectModel;
using System.IO;
using Microsoft.Win32;
using Google.GData.Client;
using System.Threading;
using System.Windows.Threading;
using System.Collections;
using System.Net;
using Microsoft.Office.Interop;

namespace GoogleDocswpfApp
{
    /// <summary>
    /// Interaction logic for UserControl.xaml
    /// </summary>
    public partial class UserControl : Window
    {
        private Google.GData.Documents.DocumentsService g_docs_service;
        private Google.GData.Documents.DocumentsListQuery g_doc_query_list;
        private Google.GData.Documents.DocumentsFeed g_doc_feed;
        private Google.GData.Documents.DocumentEntry uploaded_g_doc;
        private string[] selected_files;
        private OpenFileDialog open_dialog = new OpenFileDialog();
        private ArrayList selected_google_docs = new ArrayList();
        private const string export_url = "http://docs.google.com/feeds/download/documents/Export?docID=";
        ObservableCollection<GoogleDoc> _feeds = new ObservableCollection<GoogleDoc>();

        public UserControl(Google.GData.Documents.DocumentsService docs_service)
        {
            g_doc_query_list = new Google.GData.Documents.DocumentsListQuery();
            g_docs_service = docs_service;
            InitializeComponent();
            populateListView();
            googleDocsView.AllowDrop = true;
        }

        public System.Collections.ObjectModel.ObservableCollection<GoogleDoc> feeds
        { get { return _feeds; } }


        delegate void showDocs(GoogleDoc doc);

        private void insertGoogleDoc(GoogleDoc google_doc)
        {
            _feeds.Add(google_doc);
        }

        private void populateListView()//docid=0Adeet4yZah6mZGRnNTJ4cmRfMTR3OXpzMnZrdg
        {
            try
            {
                FoldersNode.Items.Clear();
                feeds.Clear();
                g_doc_query_list = new DocumentsListQuery();
                g_doc_query_list.ShowFolders = true;
                
                g_doc_feed = g_docs_service.Query(g_doc_query_list);
                foreach (DocumentEntry entry in g_doc_feed.Entries)
                {
                    GoogleDoc google_doc = new GoogleDoc();
                    google_doc.DocumentTitle = entry.Title.Text;
                    google_doc.DocumentLink = entry.FeedUri;
                    google_doc.DocumentId = entry.Id.AbsoluteUri;
                    google_doc.DocumentEtag = entry.Etag;
                    google_doc.DocumentResourceId = entry.AlternateUri.Content;
                    Image image = new Image();
                    ImageSource image_source;


                    if (entry.IsDocument)
                    {
                        image_source = (ImageSource)new ImageSourceConverter().ConvertFrom(@"C:\home\projects\googleDocsAPI_C\GoogleDocswpfApp\GoogleDocswpfApp\assets\Document.gif");
                        google_doc.DocumentImage = image_source;
                        google_doc.DocumentType = "Document";
                    }
                    if (entry.IsSpreadsheet)
                    {
                        image_source = (ImageSource)new ImageSourceConverter().ConvertFrom(@"C:\home\projects\googleDocsAPI_C\GoogleDocswpfApp\GoogleDocswpfApp\assets\Spreadsheet.gif");
                        google_doc.DocumentImage = image_source;
                        google_doc.DocumentType = "Spreadsheet";
                    }
                    if (entry.IsPresentation)
                    {
                        image_source = (ImageSource)new ImageSourceConverter().ConvertFrom(@"C:\home\projects\googleDocsAPI_C\GoogleDocswpfApp\GoogleDocswpfApp\assets\Presentation.gif");
                        google_doc.DocumentImage = image_source;
                        google_doc.DocumentType = "Presentation";
                    }
                    if (entry.IsStarred)
                    {
                        image_source = (ImageSource)new ImageSourceConverter().ConvertFrom(@"C:\home\projects\googleDocsAPI_C\GoogleDocswpfApp\GoogleDocswpfApp\assets\star.png");
                        google_doc.DocumentStar = image_source;
                        google_doc.DocumentStarred = true;
                    }

                    if (entry.IsFolder && entry.Title.Text != null)
                        google_doc.DocumentFolder = entry.Title.Text;

                    google_doc.DocumentModified = entry.Updated.ToShortDateString() + " " + entry.Updated.ToShortTimeString();
                    insertGoogleDoc(google_doc);
                   
                }
                lblDocCount.Content = "Documents: " + feeds.Count;
                populateTreeFolders();
                if (FoldersNode.Items.Count > 0)
                {
                    FoldersNode.IsExpanded = true;
                }
            }
            catch (Exception err)
            {
                MessageBox.Show(err.Message);
            }
        }

        private void populateTreeFolders()
        {
            foreach (GoogleDoc doc in feeds)
            {
                if (doc.DocumentFolder != null)
                    FoldersNode.Items.Add(doc.DocumentFolder);
            }
        }

        private bool uploadFile(string[] files)
        {
            try
            {
                this.Cursor = Cursors.Wait;
                foreach (string upload_file in files)
                {
                    if (upload_file.Substring(upload_file.LastIndexOf(".")) + 1 != ".xml")
                    {
                        uploaded_g_doc = g_docs_service.UploadDocument(upload_file, upload_file.Substring(upload_file.LastIndexOf(@"\") + 1));
                    }
                }
                selected_files = null;

                populateListView();
                return true;
            }
            catch (Exception err)
            {
                MessageBox.Show(err.Message, "Error", MessageBoxButton.OKCancel, MessageBoxImage.Exclamation);
                return false;
            }
        }

        private void exportFile() //"http://docs.google.com/feeds/documents/private/full/document%3A0Adeet4yZah6mZGRnNTJ4cmRfMzhwejRucjdkaA"
        {
            try //"http://docs.google.com/Doc?docid=0Adeet4yZah6mZGRnNTJ4cmRfMzhwejRucjdkaA&hl=en"
            {
                GoogleDoc selected_google_doc = googleDocsView.SelectedItem as GoogleDoc;
                string resource_id = selected_google_doc.DocumentResourceId.Substring(selected_google_doc.DocumentResourceId.IndexOf("docid=") + 6);
                resource_id = resource_id.Substring(0, resource_id.LastIndexOf("=en"));

                setupSaveDialog(selected_google_doc.DocumentType, resource_id, selected_google_doc.DocumentEtag, selected_google_doc.DocumentTitle);
            }
            catch (Exception err)
            {
            }
        }

        private void setupSaveDialog(string default_docType, string resourceID, string eTag, string docTitle)
        {

            SaveFileDialog save_file_dialog = new SaveFileDialog();
            save_file_dialog.Title = "Export file to..";

            save_file_dialog.Filter = "Microsoft Word |*.doc|HTML |*.html|Open Document Format |*.odt|Portable Document Format |*.pdf" +
                                      "|Rich Format|*.rtf|TXT File|*.txt|ZIP archive|*.zip |Portable Networks Graphic Image Format|*.png |All Files |*.*";
            save_file_dialog.FileName = docTitle;
            save_file_dialog.ShowDialog();

            if (save_file_dialog.FileName != "")
            {
                FileStream filestream = (FileStream)save_file_dialog.OpenFile();
                Stream google_docs_stream = null;
                string export_full_url = string.Empty;
                int nbytes = 2048;
                int count = 0;
                Byte[] arr = new Byte[nbytes];
                switch (save_file_dialog.FilterIndex)
                {
                    case 1:
                        {
                            resourceID += "&exportFormat=" + "doc";
                            export_full_url += export_url + resourceID;
                            google_docs_stream = g_docs_service.Query(new Uri(export_full_url), eTag);
                            if (google_docs_stream != null)
                            {
                                do
                                {
                                    count = google_docs_stream.Read(arr, 0, nbytes);
                                    filestream.Write(arr, 0, count);
                                } while (count > 0);
                            }
                            filestream.Close();
                            arr = null;
                            break;
                        }
                    case 2:
                        {
                            resourceID += "&exportFormat=" + "html";
                            export_full_url += export_url + resourceID;
                            google_docs_stream = g_docs_service.Query(new Uri(export_full_url), eTag);
                            if (google_docs_stream != null)
                            {
                                do
                                {
                                    count = google_docs_stream.Read(arr, 0, nbytes);
                                    filestream.Write(arr, 0, count);
                                } while (count > 0);
                            }
                            filestream.Close();
                            arr = null;
                            break;
                        }
                    case 3:
                        {
                            resourceID += "&exportFormat=" + "odt";
                            export_full_url += export_url + resourceID;
                            google_docs_stream = g_docs_service.Query(new Uri(export_full_url), eTag);
                            if (google_docs_stream != null)
                            {
                                do
                                {
                                    count = google_docs_stream.Read(arr, 0, nbytes);
                                    filestream.Write(arr, 0, count);
                                } while (count > 0);
                            }
                            filestream.Close();
                            arr = null;
                            break;
                        }
                    case 4:
                        {
                            resourceID += "&exportFormat=" + "pdf";
                            export_full_url += export_url + resourceID;
                            google_docs_stream = g_docs_service.Query(new Uri(export_full_url), eTag);

                            if (google_docs_stream != null)
                            {
                                do
                                {
                                    count = google_docs_stream.Read(arr, 0, nbytes);
                                    filestream.Write(arr, 0, count);
                                } while (count > 0);
                            }
                            filestream.Close();
                            arr = null;
                            break;
                        }
                    case 5:
                        {
                            resourceID += "&exportFormat=" + "rtf";
                            export_full_url += export_url + resourceID;
                            google_docs_stream = g_docs_service.Query(new Uri(export_full_url), eTag);
                            if (google_docs_stream != null)
                            {
                                do
                                {
                                    count = google_docs_stream.Read(arr, 0, nbytes);
                                    filestream.Write(arr, 0, count);
                                } while (count > 0);
                            }
                            filestream.Close();
                            arr = null;
                            break;
                        }
                    case 6:
                        {
                            resourceID += "&exportFormat=" + "txt";
                            export_full_url += export_url + resourceID;
                            google_docs_stream = g_docs_service.Query(new Uri(export_full_url), eTag);
                            if (google_docs_stream != null)
                            {
                                do
                                {
                                    count = google_docs_stream.Read(arr, 0, nbytes);
                                    filestream.Write(arr, 0, count);
                                } while (count > 0);
                            }
                            filestream.Close();
                            arr = null;
                            break;
                        }
                    case 7:
                        {
                            resourceID += "&exportFormat=" + "zip";
                            export_full_url += export_url + resourceID;
                            google_docs_stream = g_docs_service.Query(new Uri(export_full_url), eTag);
                            if (google_docs_stream != null)
                            {
                                do
                                {
                                    count = google_docs_stream.Read(arr, 0, nbytes);
                                    filestream.Write(arr, 0, count);
                                } while (count > 0);
                            }
                            filestream.Close();
                            arr = null;
                            break;
                        }
                    case 8:
                        {
                            resourceID += "&exportFormat=" + "png";
                            export_full_url += export_url + resourceID;
                            google_docs_stream = g_docs_service.Query(new Uri(export_full_url), eTag);
                            if (google_docs_stream != null)
                            {
                                do
                                {
                                    count = google_docs_stream.Read(arr, 0, nbytes);
                                    filestream.Write(arr, 0, count);
                                } while (count > 0);
                            }
                            filestream.Close();
                            arr = null;
                            break;
                        }
                    default:
                        break;
                }
            }


            //Stream google_response_stream = g_docs_service.Query(new Uri("http://docs.google.com/feeds/download/documents/Export?docID=" + resource_id + "&exportFormat=doc"), selected_google_doc.DocumentEtag);
            //FileStream filestream = new FileStream(@"c:\home\test.doc", FileMode.Create);
            //if (google_response_stream != null)
            //{
            //    int nbytes = 4096;
            //    int count = 0;

            //    Byte[] arr = new Byte[nbytes];
            //    do
            //    {
            //        count = google_response_stream.Read(arr, 0, nbytes);
            //        filestream.Write(arr, 0, count);

            //    } while (count > 0);
            //    filestream.Close();

            //}
            //google_response_stream.Close();
        }

        private void googleDocsView_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            try
            {
                selected_google_docs.Remove(googleDocsView.SelectedItem as GoogleDoc);
                selected_google_docs.Add(googleDocsView.SelectedItem as GoogleDoc);
                if (feeds.Count > 0)
                    setupContextMenu();
            }
            catch (Exception err)
            {
            }
            finally
            {

            }
        }

        private void setupContextMenu()
        {
            GoogleDoc google_doc = googleDocsView.SelectedItem as GoogleDoc;
            context_docTitle.Header = google_doc.DocumentTitle;
            context_docImage.Source = google_doc.DocumentImage;
            context_docModified.Header = google_doc.DocumentModified;
        }

        private void context_bin_Click(object sender, RoutedEventArgs e)
        {
            deleteDocument();
        }

        private void deleteDocument()
        {
            try
            {
                GoogleDoc google_doc = googleDocsView.SelectedItem as GoogleDoc;

                if (MessageBox.Show("Are you sure you want to delete the document?", "Deleting document", MessageBoxButton.YesNo, MessageBoxImage.Information) == MessageBoxResult.Yes)
                {
                    g_docs_service.Delete(new Uri(google_doc.DocumentId), google_doc.DocumentEtag);
                    selected_google_docs.Remove(google_doc);
                }
                populateListView();
            }
            catch (Exception err)
            {

            }
        }

        private void googleDocsView_Drop(object sender, DragEventArgs e)
        {
            this.Cursor = Cursors.Hand;
            uploadFile(selected_files);
            this.Cursor = Cursors.Arrow;
        }

        private void googleDocsView_DragOver(object sender, DragEventArgs e)
        {
            if (e.Data.GetDataPresent(DataFormats.FileDrop))
            {
                selected_files = null;
                selected_files = e.Data.GetData(DataFormats.FileDrop) as string[];
            }
        }

        private void Grid_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.Key == Key.Delete && googleDocsView.SelectedItem != null)
                deleteDocument();
        }

        private void buttonSignout_Click(object sender, RoutedEventArgs e)
        {
            g_docs_service = null;
            selected_files = null;
            Window1 login = new Window1();
            login.Show();
            this.Close();

        }

        private void Export_Click(object sender, RoutedEventArgs e)
        {
            exportFile();
        }

        private void context_star_Click(object sender, RoutedEventArgs e)
        {

        }

        private void googleDocsView_PreviewDragOver(object sender, DragEventArgs e)
        {

        }

        private void buttonReload_Click(object sender, RoutedEventArgs e)
        {
            populateListView();
        }

        private void treeViewDocs_SelectedItemChanged(object sender, RoutedPropertyChangedEventArgs<object> e)
        {
            if (!e.NewValue.ToString().Equals("My Folders"))
            {
                changeColor(e.NewValue.ToString());
            }
        }

        private void changeColor(string folderName)
        {
            foreach (GoogleDoc doc in feeds)
            {
                if (doc.DocumentFolder != null && doc.DocumentFolder.Equals(folderName))
                {
                    
                }
            }
        }



    }
}
